﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Data;
using System.IO;

using MySql.Data.MySqlClient;

using BASE;


namespace DL_Builder__MySQL
{
	public partial class DL_Builder__MySQL : Form
	{
		public DL_Builder__MySQL()
		{
			InitializeComponent();
		}


		private void DL_Builder__MySQL_Load(object sender, EventArgs e)
		{
			func_init();
		}


		public void func_init()
		{
			txt_tmpl_path.Text = Application.StartupPath.Replace(@"bin\Debug", "") + @"tmpl\__tmpl__.txt";

			var str_db_conn = WebHelper.func_get_appsetings("MySQL");
			compDBLink.Text = str_db_conn;

			//所以数据库
			{
				var sql = "SHOW DATABASES;";

				var dt = MySQLHelper.ExecuteDataTable(sql);
				cb_database.Items.Add("全部");
				foreach (DataRow row in dt.Rows)
				{
					if (row["Database"].ToString().Contains("x_")
						|| row["Database"].ToString().Contains("test"))
					{
						cb_database.Items.Add(row["Database"]);
					}
				}
			}

			cb_database.Text = "全部";
		}


		private void cb_allselect_CheckedChanged(object sender, EventArgs e)
		{
			var isChecked = cb_allselect.Checked;
			int count = clb_table.Items.Count;
			for (int i = 0; i < count; i++)
			{
				clb_table.SetItemChecked(i, isChecked);
			}
		}

		private void btn_file_Click(object sender, EventArgs e)
		{
			var fd = new FolderBrowserDialog();
			if (fd.ShowDialog() == DialogResult.OK)
			{
				txt_fliepath.Text = fd.SelectedPath;
			}
		}

		private void cb_database_SelectedIndexChanged(object sender, EventArgs e)
		{
			clb_table.Items.Clear();
			cb_allselect.Checked = false;

			var database_list = new List<string>();
			if (cb_database.Text == "全部")
			{
				for (int i = 1; i < cb_database.Items.Count; i++)
				{
					database_list.Add(cb_database.Items[i].ToString());
				}
			}
			else
			{
				database_list.Add(cb_database.Text);
			}


			foreach (var database_str in database_list)
			{
				var sql = "SHOW TABLES FROM {0};".J_Format(database_str);

				var dt = MySQLHelper.ExecuteDataTable(sql);
				foreach (DataRow row in dt.Rows)
				{
					clb_table.Items.Add(database_str + "." + row[0]);
				}
			}
		}


		//生成通用实体
		private void btn_gencode_laravel_Click(object sender, EventArgs e)
		{
			if (txt_fliepath.Text.J_IsNullOrEmpty())
			{
				MessageBox.Show("请选择保存路径");

				return;
			}

			if (txt_tmpl_path.Text.J_IsNullOrEmpty())
			{
				MessageBox.Show("请选择模版路径");

				return;
			}


			//进度条
			{
				progressBar1.Value = 0;
				progressBar1.Maximum = clb_table.Items.Count;
			}


			for (int i = 0; i < clb_table.Items.Count; i++)
			{
				if (clb_table.GetItemChecked(i))
				{
					var data = clb_table.Items[i].J_ToString().Split('.');
					var db_name = data[0];
					var tb_name = data[1];

					func_gen_tb_class__laravel(db_name, tb_name);
				}

				progressBar1.Value++;
			}
		}


		private void func_gen_tb_class__laravel(string db_name, string tb_name)
		{
			var tmpl = FileHelper.func_get_content(txt_tmpl_path.Text);

			var builder = new StringBuilder(tmpl);


			//添加字段提示
			var sql = string.Format("show columns from {0}.{1};", db_name, tb_name);
			var tb_columns_dt = MySQLHelper.ExecuteDataTable(sql);

			var fields = "";
			var prefix = "";
			var property = "";
			foreach (DataRow row in tb_columns_dt.Rows)
			{
				var field = row["Field"].ToString();

				var type = row["Type"].ToString();
				if (type == "datetime")
				{
					fields += "\t/** @var \\Carbon\\Carbon */\r\n".J_Format(field);
					fields += "\tprotected ${0};\r\n".J_Format(field);
					//					fields += @"
					//\\t/** @var \Carbon\Carbon */
					//\\tpublic ${0};\\r\\n".J_Format(field);

					property += " * @property \\Carbon\\Carbon ${0};\r\n".J_Format(field);
				}
				else
				{
					fields += "\tprotected ${0};\r\n".J_Format(field);

					property += " * @property ${0};\r\n".J_Format(field);
				}

				var prefix_data = field.Split('_');
				prefix = prefix_data[0] + "_";
			}


			builder.Replace("{$db}", db_name);
			builder.Replace("{$table}", tb_name);
			builder.Replace("{$prefix}", prefix);
			builder.Replace("{$fields}", fields);
			builder.Replace("{$property}", property);


			#region 文件保存
			{
				var file_path = @"{0}\{1}.php".J_Format(txt_fliepath.Text, string.Format("__{0}", tb_name));
				if (File.Exists(file_path))
				{
					File.Delete(file_path);
				}
				File.AppendAllText(file_path, builder.ToString());
			}
			#endregion
		}

		//修改
		private void button2_Click(object sender, EventArgs e)
		{
			func_init();
		}


	}//class

}//namespace
